package nc.ui.am.common;

import java.util.ArrayList;
import java.util.List;

import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;


public class TaskThreadPool {
	// Count of available or free threads.
	private int freeCount;

	// Total number of threads.
	private int threadCount;

	private List tasksList = new ArrayList();

	private MyCallback callback = new MyCallback();

	/**
	 * Add a task to be executed by the next available thread
	 * in this thread pool. If there is no free thread available
	 * but the maximum number of threads hasn't been reached then
	 * create a new thread.
	 */
	public synchronized void addTask(Runnable task) throws IllegalArgumentException {
		if (task == null) {
			throw new IllegalArgumentException("Null Runnable passed");
		}
		tasksList.add(task);
		// Should there me a Max Number of threads?
		if (freeCount == 0) {
			Thread th = new Thread(new TaskExecuter(callback));
			th.setPriority(Thread.MIN_PRIORITY); //??
			th.setDaemon(true);
			th.start();
			++threadCount;
		} else {
			synchronized (callback) {
				callback.notify();
			}
		}
	}

	private final class MyCallback implements ITaskThreadPoolCallback {
		public void incrementFreeThreadCount() {
			++freeCount;
		}

		public void decrementFreeThreadCount() {
			--freeCount;
		}

		public synchronized Runnable nextTask() {
			if (tasksList.size() > 0) {
				return (Runnable) tasksList.remove(0);
			}
			return null;
		}

		public void showMessage(final Throwable th) {
			
			SwingUtilities.invokeLater(new Runnable() {
				public void run() {
					//i18n[TaskThreadPool.errorDuringTaskExecMsg=Error ocured during task execution:]
					StringBuffer msg = new StringBuffer(th.getMessage());
					msg.append("\n");
					msg.append(th.getMessage());
					JOptionPane.showMessageDialog(null, msg.toString());
					throw new RuntimeException(th);
				}
			});
		}
	}
}
